<?php

require('functions/settings.php');
require('functions/dbConn.php');
require('functions/loginRequired.php');
require('functions/buildLinks.php');
require('functions/averageFeedback.php');
require('functions/hiddenQS.php');
require('functions/pageSelector.php');


//Change By Vyas Ishan 17 May 2013 Task2
//Setting the GLOBAL variables $META_KEYWORDS to set the meta keywords in the meta tags.
$META_KEYWORDS = '';
//Change By Vyas Ishan 17 May 2013 Task2

// load in settings

$settingsQuery = "SELECT * FROM settings";
$settingsResult=mysql_query( $settingsQuery ) or die ("Error in query: $settingsQuery. " . mysql_error());
while($settingsArr=mysql_fetch_assoc($settingsResult)){
$settings[$settingsArr['setting_name']] = $settingsArr['setting_value'];
}

session_start();

// cookie?

if(!isset($_SESSION['user']) && isset($_COOKIE['web']) && !isset($_SESSION['signing_out'])){

	$cookie = explode("_",$_COOKIE['web']);

	$sql = "SELECT id, tradesman FROM users WHERE id = '".mysql_real_escape_string($cookie[0])."' AND password = '".mysql_real_escape_string($cookie[1])."' AND banned != 1";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$rows=mysql_num_rows($query);
	
	if($rows == 1){

	$_SESSION['user'] = $rs['id'].'_'.$_SERVER['REMOTE_ADDR'];

	$sql = "UPDATE users SET last_login = '".date("Y-m-d H:i:s")."' WHERE id = '".$rs['id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$_SESSION['tradesman'] = $rs['tradesman'];

	}

	else{
	setcookie("web", "", time() - 3600,"/");
	}

}

// logging in?

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['email_address']) && isset($_POST['password'])){

	$encrypt1 = base64_encode($_POST['password'].'_'.$encryption_salt);
	$encrypt2 = md5($encrypt1.'_'.$_POST['email_address'].'_'.$encryption_salt);
//	echo $encrypt2;

	$sql = "SELECT id, tradesman FROM users WHERE email = '".mysql_real_escape_string($_POST['email_address'])."' AND password = '".$encrypt2."' AND banned != 1";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$rows=mysql_num_rows($query);

	if($rows == 1){

	$_SESSION['user'] = $rs['id'].'_'.$_SERVER['REMOTE_ADDR'];

	$sql = "UPDATE users SET last_login = '".date("Y-m-d H:i:s")."' WHERE id = '".$rs['id']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$_SESSION['tradesman'] = $rs['tradesman'];

	if($_POST['remember'] == '1'){
	$cookie = $rs['id'].'_'.$encrypt2;
	setcookie("web", $cookie, time()+60*60*24*365*10,"/");  /* expire in 10 years */
	}

	if(isset($_GET['ref'])){

	header("Location: ".urldecode($_GET['ref']));

	}

	else{

	header("Location: /my-account");

	}

	}

	else{
	$login_result = '<span id="login_error">Incorrect email address or password.</span>';
	}
}

if(isset($_SESSION['signing_out'])){

unset($_SESSION['signing_out']);

}

function get_banner_ad($banner_type, $banner_area_type){

if(isset($_SESSION['user'])){
$banner_area_type = ($_SESSION['tradesman'] == '1') ? 'tradesman_area' : 'user_area';
}

switch($banner_type){

case "content_banner":
$banner_type_id = 1;
$sql = "SELECT code FROM adverts WHERE ".$banner_area_type." = 1 AND type = ".$banner_type_id." ORDER BY RAND() LIMIT 1";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rs=mysql_fetch_assoc($query);
$rows = mysql_num_rows($query);
$content = ($rows == 1) ? '<div id="'.$banner_type.'">'.$rs['code'].'</div>' : '' ;
break;

case "column_banner":
$banner_type_id = 2;
$sql = "SELECT code FROM adverts WHERE ".$banner_area_type." = 1 AND type = ".$banner_type_id." ORDER BY RAND() LIMIT 2";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rows = mysql_num_rows($query);
if($rows > 0){
	$content='<div id="'.$banner_type.'">';
	while($rs=mysql_fetch_assoc($query)){
	$content.='<div style="float: left; width: 120px;">'.$rs['code'].'</div>';
	}
	$content.='</div>';
}
break;

}

return $content;

}

function distance_calc($lat1, $lon1, $lat2, $lon2, $unit) { 

  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

function createRandomPassword(){

    $chars = strtoupper("abcdefghjkmnpqrtuvwxyz2346789");
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= 8) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass.= $tmp;
        $i++;
    }
    return $pass;
}

function get_ad($placement){

	// if tradesman search

	if(isset($_GET['trade']) && strlen($_GET['trade']) > 0){

	$sql = "SELECT img, code, link FROM banners 
			LEFT JOIN banners_to_trades ON banners.id = banners_to_trades.banner_id 
			LEFT JOIN trades ON banners_to_trades.trade_id = trades.id 
			WHERE published = 1 AND trades.url = '".mysql_real_escape_string($_GET['trade'])."' AND placement = '".$placement."'
			ORDER BY RAND()
			LIMIT 0,1";
	$query = mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
	$rs = mysql_fetch_assoc($query);
	$rows = mysql_num_rows($query);
	
		if($rows > 0){
		$banner = (strlen($rs['img']) > 0) ? '<div class="banner"><a href="'.$rs['link'].'"><img src="/images/banners/'.$rs['img'].'" alt=""></a></div>' : '<div class="banner">'.$rs['code'].'</div>';
		}

	}

	// else if tradesman profile

	elseif(isset($_GET['trades']) && strlen($_GET['trades']) > 0){

	$trades_sql = array();
	
	$sql = "SELECT id, url FROM trades";
	$query = mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
	while($rs = mysql_fetch_assoc($query)){
	
		if(strpos($_GET['trades'], $rs['url']) !== false){
		$trades_sql[] = "banners_to_trades.trade_id = ".$rs['id'];
		}
	
	}
	
	$sql = "SELECT img, code, link FROM banners 
			LEFT JOIN banners_to_trades ON banners.id = banners_to_trades.banner_id 
			WHERE published = 1 AND (".implode(' OR ', $trades_sql).") AND placement = '".$placement."'
			ORDER BY RAND()
			LIMIT 0,1";
	$query = mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
	$rs = mysql_fetch_assoc($query);
	$rows = mysql_num_rows($query);
	
		if($rows > 0){
		$banner = (strlen($rs['img']) > 0) ? '<div class="banner"><a href="'.$rs['link'].'"><img src="/images/banners/'.$rs['img'].'" alt=""></a></div>' : '<div class="banner">'.$rs['code'].'</div>';
		}
	
	}

	else{
	// do nothing
	}
	
	if(strlen($banner) == 0){
	// load random
	
		$sql = "SELECT img, code, link FROM banners WHERE published = 1 AND placement = '".$placement."' ORDER BY RAND() LIMIT 0,1";
		$query = mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
		$rs = mysql_fetch_assoc($query);
		$rows = mysql_num_rows($query);
		
		if($rows > 0){
		$banner = (strlen($rs['img']) > 0) ? '<div class="banner"><a href="'.$rs['link'].'"><img src="/images/banners/'.$rs['img'].'" alt=""></a></div>' : '<div class="banner">'.$rs['code'].'</div>';
		}
	
	}
	
	return (strlen($banner) > 0) ? $banner : false;

}

?>